<template>
    <view class="input-container">
        <view
            class="input-box"
            v-for="(char, index) in 8"
            :key="index"
            @click="handleInputBoxClick(index)"
            :class="{ focused: focusedIndex === index }"
        >
            <span class="license-plate-input-text">{{ inputCharsArray[index] }}</span>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})

// 只在第一次初始化值，后续不在此修改，应用编辑
const editInitModelValue = ref(false)
watch(
    () => props.modelValue,
    (newVal) => {
        if (editInitModelValue.value) {
            return
        }
        inputCharsArray.value = newVal.split('')
        editInitModelValue.value = true
    }
)

const emit = defineEmits(['update:modelValue', 'focus'])

const inputCharsArray = ref(Array(8).fill(''))
const focusedIndex = ref(0)

const handleInputBoxClick = (index) => {
    focusedIndex.value = index
    emitFocus()
}

// 设值事件
const setInputValue = (key) => {
    if (focusedIndex.value !== -1) {
        inputCharsArray.value[focusedIndex.value] = key
        updateModelValue()
        if (focusedIndex.value < 7) {
            focusedIndex.value++
            emitFocus()
        }
    }
}

// 删除事件
const deleteInputValue = () => {
    if (focusedIndex.value !== -1) {
        // 如果当前聚焦有值，重置值
        if (inputCharsArray.value[focusedIndex.value]) {
            inputCharsArray.value[focusedIndex.value] = ''
        } else if (focusedIndex.value > 0) {
            // 如果当前聚焦没有值，则后退，再重置值
            focusedIndex.value--
            inputCharsArray.value[focusedIndex.value] = ''
            emitFocus()
        }
        updateModelValue()
    }
}

const emitFocus = () => {
    emit('focus', focusedIndex.value)
}

// 更新事件
const updateModelValue = () => {
    emit('update:modelValue', inputCharsArray.value.join(''))
}

defineExpose({
    blur: () => {
        focusedIndex.value = -1
    },
    setInputValue,
    deleteInputValue
})
</script>

<style lang="less">
.input-container {
    width: 686px;
    display: flex;
    justify-content: space-between;
}

.input-box {
    background-color: #efefef;
    padding: 8px;
    font-size: 16px;
    border-radius: 8px;
    box-sizing: border-box;
    width: 64px;
    height: 74px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    box-sizing: border-box;
    &:nth-child(2) {
        margin-right: 32px;
        &:after {
            content: '';
            width: 8px;
            height: 8px;
            background-color: #1d9634;
            position: absolute;
            top: calc(50% - 4px);
            right: -32px;
            border-radius: 50%;
        }
    }
}

.input-box.focused {
    border: 2px solid #1d9634;
}

.license-plate-input-text {
    font-size: 32px;
    color: #1d9634;
}
</style>
